﻿using Quartz;
using Quartz.Impl;
using Quartz.Impl.Triggers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ByteSite.Quartz
{
    public static class QuartzNETExtension
    {
        private static List<Entitys.QuartzTask> _taskList = new BLL.quartz_task().GetList(x => x.delete_flag == 0, x => x.id);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>通过作业上下文获取作业对应的配置参数
        /// <returns></returns>
        public static Entitys.QuartzTask GetTaskOptions(this IJobExecutionContext context)
        {
            AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
            Entitys.QuartzTask taskOptions = _taskList.Where(x => x.id.ToString() == trigger.Name && x.group == trigger.Group).FirstOrDefault();
            return taskOptions ?? _taskList.Where(x => x.id.ToString() == trigger.JobName && x.group == trigger.JobGroup).FirstOrDefault();
        }

        /// <summary>
        /// 作业是否存在
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <param name="init">初始化的不需要判断</param>
        /// <returns></returns>
        public static (bool, object) Exists(this Entitys.QuartzTask taskOptions, bool init)
        {
            if (!init && _taskList.Any(x => x.id == taskOptions.id && x.group == taskOptions.group))
            {
                return (false,
                    new
                    {
                        status = false,
                        msg = $"作业:{taskOptions.id.ToString()},分组：{taskOptions.group}已经存在"
                    });
            }
            return (true, null);
        }

        public static (bool, string) IsValidExpression(this string cronExpression)
        {
            try
            {
                CronTriggerImpl trigger = new CronTriggerImpl();
                trigger.CronExpressionString = cronExpression;
                DateTimeOffset? date = trigger.ComputeFirstFireTimeUtc(null);
                return (date != null, date == null ? $"请确认表达式{cronExpression}是否正确!" : "");
            }
            catch (Exception e)
            {
                return (false, $"请确认表达式{cronExpression}是否正确!{e.Message}");
            }
        }
    }
}
